package com.otto.reggie.common;

import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局controller异常处理
 * 作者：otto
 * 时间：2022-07-20 19:27:12
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 异常处理方法
     *
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.error(ex.getMessage());
        if (ex.getMessage().contains("Duplicate entry")) {
            String [] split = ex.getMessage().split(" ");
            String name =split[2];
            return R.error(name+" 重复了。");
        }
        return R.error("未知错误！");
    }
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex) {
        log.error(ex.getMessage());
        /*if (ex.getMessage().contains("Duplicate entry")) {
            String [] split = ex.getMessage().split(" ");
            String name =split[2];
            return R.error(name+" 重复了。");
        }*/
        return R.error(ex.getMessage());
    }
}
